/**事务消息生产者
 * 最大的不同是要设置TransactionListener，在其中完成事务和检查结果
 */

import org.apache.rocketmq.client.exception.MQClientException;

import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.*;

public class TransactionProducer {
    public static void main(String[] args) throws MQClientException, InterruptedException {
        TransactionListener transactionListener = new TransactionListenerImpl();
        TransactionMQProducer producer = new TransactionMQProducer("my_transacton_group");
        producer.setNamesrvAddr("localhost:9876");
        producer.setTransactionListener(transactionListener);
        producer.start();

        String[] tags = new String[] {"TransactionA", "TransactionB", "TransactionC", "TransactionD", "TransactionE"};
        for (int i = 0; i < 10; i++) {
            try {
                Message msg =
                    new Message("TopicTransaction", tags[i % tags.length], "KEY" + i,
                        ("Hello RocketMQ Transaction" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.sendMessageInTransaction(msg, null);
                //重载方法：sendMessageInTransaction(Message msg,LocalTransactionExecuter tranExecuter, Object arg)
                System.out.printf("%s%n", sendResult);

                TimeUnit.MICROSECONDS.sleep(1000);
            } catch (MQClientException | UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }

        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                producer.shutdown();
            }
        }));

//        for (int i = 0; i < 100000; i++) {
//            Thread.sleep(1000);
//        }
//        producer.shutdown();
    }
}
